package com.bjsxt.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.bjsxt.meta.User;
import com.bjsxt.utils.BaseDao;

public class UserDao extends BaseDao {

	public boolean login(User user) {
		if("bjsxt".equals(user.getUsername()) && "123".equals(user.getPassword())){
			return true;
		}else{
			return false;
		}
	}
	
	public List<User> list(){
		List<User> users = new ArrayList<User>();
		ResultSet rs = this.getResultSet("select id,username,password,age,email from t_user");
		try {
			while(rs.next()){
				User user = new User(rs.getInt("id"), rs.getString("username"), rs.getString("password"), rs.getInt("age"), rs.getString("email"));
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		this.closeAll();
		return users.size()>0?users:null;		
	}
	
	public int add(User user){
		return this.executeUpdate("insert into t_user (username,age,email)values(?,?,?)", user.getUsername(),user.getAge(),user.getEmail());
	}
	
	public int del(User user){
		return this.executeUpdate("delete from t_user where id=?", user.getId());
	}
	
	public User getUserById(User user){
		User u = new User();
		ResultSet rs = this.executeQuery("select id,username,age,email from t_user where id=?", user.getId());
		try {
			if(rs.next()){
				u.setId(rs.getInt("id"));
				u.setUsername(rs.getString("username"));
				// u.setPassword(rs.getString("password"));
				u.setAge(rs.getInt("age"));
				u.setEmail(rs.getString("email"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return u;
	}
	
	public int update(User user){
		return this.executeUpdate("update t_user set username=?,age=?,email=? where id=?", user.getUsername(),user.getAge(),user.getEmail(),user.getId());		
	}
	
}
